
#include"glheader.h"
#include"vshape.h"
#include<math.h>

struct vertattrib{
  int id;
  int size;
  int type;
  int normalize;
  int stride;
  float * pointer;
  VertAttrib * next;
  vertattrib (int _id,int _size,int _type,int _normalize,int _stride,float * _pointer):
    id(_id),size(_size),type(_type),normalize(_normalize),
    stride(_stride),pointer(_pointer),next(NULL)
  {};
};

VShape::VShape ()
{
  a_normal   = new VertAttrib(0,3,GL_FLOAT,GL_FALSE,0,NULL);
  a_vertices = new VertAttrib(0,3,GL_FLOAT,GL_FALSE,0,NULL);
  attrib_list = a_normal;
  a_normal->next = a_vertices;
}

void VShape::GetBBox (float* xmi, float* xma, 
                float* ymi, float* yma, 
                float* zmi, float* zma)
  {
    *xmi = xmin;   *xma = xmax;
    *ymi = ymin;   *yma = ymax;
    *zmi = zmin;   *zma = zmax;
  }

void VShape::SetNormalId(int id)
{
  a_normal->id = id;
}

void VShape::SetVertId(int id)
{
  a_vertices->id = id;
}

float * VShape::GetNormalArray ()
{
  return a_normal->pointer;
}


float * VShape::GetVertArray ()
{
  return a_vertices->pointer;
}

unsigned int * VShape::GetTriangleArray ()
{
  return triangles;
}

void VShape::SetNormalArray (float * a)
{
  a_normal->pointer = a;
}

void VShape::SetVertArray (float * a)
{
  a_vertices->pointer = a;
}

void VShape::AddVertAttrib (int _id,int _size,int _type,int _normalize,int _stride,float * _pointer)
{
  VertAttrib * new_att = new VertAttrib(_id,_size,_type,_normalize,_stride, _pointer);
  new_att->next = attrib_list;
  attrib_list = new_att;
}
 
void VShape::Draw ()
{
  //glEnable(GL_CULL_FACE);
  glEnableClientState(GL_VERTEX_ARRAY);
  VertAttrib * elem = attrib_list;
  while(elem){
    glEnableVertexAttribArray(elem->id);
    elem = elem->next;
  }
  elem = attrib_list;
  while(elem){
    glVertexAttribPointer(elem->id,elem->size,elem->type,elem->normalize,elem->stride,elem->pointer);
    elem = elem->next;
  }
  glDrawElements(GL_TRIANGLES, 3*n_triangles,  GL_UNSIGNED_INT, triangles);
  elem = attrib_list;
  while(elem){
    glDisableVertexAttribArray(elem->id);
    elem = elem->next;
  }
  glDisableClientState(GL_VERTEX_ARRAY);
}

  //if(tex){
    //glEnableVertexAttribArray(t_id);
    //glVertexAttribPointer(t_id,2,GL_FLOAT,GL_FALSE,0, tex_coord);
  //}

void vs_normalize (float v[3])
{
	float d = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
  if(d==0)
    return;
  v[0] = v[0]/d;
	v[1] = v[1]/d;
	v[2] = v[2]/d;
}

void vs_normcrossprod(float v1[3], float v2[3], float out[3])
{
	out[0] = v1[1]*v2[2] - v1[2]*v2[1];
	out[1] = v1[2]*v2[0] - v1[0]*v2[2];
	out[2] = v1[0]*v2[1] - v1[1]*v2[0];
	vs_normalize(out);
}

